<?php

namespace catchAdmin\basics\controller;

use catchAdmin\basics\service\EdiService;
use catchAdmin\stock\model\MoveMain;
use catchAdmin\storehouse\model\WarehouseOut;
use catchAdmin\storehouse\model\WarehouseOutSon;
use catchAdmin\storehouse\model\Warehousing;
use catchAdmin\storehouse\model\WarehousingSon;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\basics\model\AddData as AddDataModel;
use catcher\CatchAuth;
use catchAdmin\basics\request\AddDataCreateRequest;
use otherLibrary\FTPClient;
use think\Exception;
use think\facade\Db;
use think\facade\Request as ThinkRequest;

class AddData extends CatchController
{
    
    protected $addDataModel;
    
    /**
     *
     * @time 2022/02/28 15:16
     * @param AddDataModel $addDataModel
     * @return mixed
     */
    public function __construct(AddDataModel $addDataModel)
    {
        $this->addDataModel = $addDataModel;
    }
    
    /**
     * 列表
     * @time 2022/02/28 15:16
     * @return \think\response\Json
     */
    public function index(CatchAuth $auth)
    {
        $user=$auth->user();
        return CatchResponse::paginate($this->addDataModel->getList($user['tenant_id']));
    }
    /**
     * 新建
     * @param CatchAuth $auth
     * @param AddDataCreateRequest $request
     * @return \think\response\Json
     */
    public function create(CatchAuth $auth,AddDataCreateRequest $request)
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['corresponding_business'] = implode(',',$params['corresponding_business']);
        return CatchResponse::success($this->addDataModel->storeBy($params),'新建成功');
    }
    /**
     * 更新
     * @time 2022/02/28 15:16
     * @param AddDataCreateRequest $request
     * @return \think\response\Json
     */
    public function update(AddDataCreateRequest $request)
    {
        $params = $request->filterEmptyField()->post();
        $params['corresponding_business'] = implode(',',$params['corresponding_business']);
        return CatchResponse::success($this->addDataModel->updateBy($params['id'], $params),'修改成功');
    }
    
    /**
     * 删除
     * @time 2022/02/28 15:16
     * @param Request $request
     * @return \think\response\Json
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        return CatchResponse::success($this->addDataModel->deleteBy($id),'删除成功');
    }

    /**
     * 其他信息
     * @time 2022/02/28 15:16
     * @param Request $request
     * @return \think\response\Json
     */
    public function getOther(Request $request)
    {
        $type = $request->post('type');
        $where = [];
        $where[] = ['deleted_at','=',0];
        $where[] = ['corresponding_business','like','%'.$type.'%'];
        $data = $this->addDataModel->where($where)->withoutField('tenant_id,updated_at,deleted_at,created_at,creator_id')->select()->toArray();

        $arr = [];
        for($i=0;$i<ceil(count($data)/3);$i++){
              $arr[$i] = array_slice($data,$i*3,3);
        }
        return CatchResponse::success($arr,'查询成功');
    }

    public function getTreeData1()
    {
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $treeData = $this->readDirectory($baseDir);

        // 按照文件创建时间倒序排序
        $this->sortByCreateTimeDesc($treeData);

        return CatchResponse::success($treeData,'查询成功');

//        return json(['data' => $treeData]);
    }

    private function readDirectory($dir)
    {
        $result = [];
        $files = scandir($dir);

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $filePath = $dir . DIRECTORY_SEPARATOR . $file;
            $fullPath = realpath($filePath);  // 获取完整路径

            if (is_dir($filePath)) {
                $result[] = [
                    'label' => $file,
                    'path' => $fullPath,  // 存储完整路径
                    'children' => $this->readDirectory($filePath)
                ];
            } else {
                $result[] = [
                    'path' => $fullPath,  // 存储完整路径
                    'label' => $file
                ];
            }
        }

        return $result;
    }

    private function sortByCreateTimeDesc(&$treeData)
    {
        // 使用 usort 函数按照创建时间倒序排列
        usort($treeData, function ($a, $b) {
            $fileA = $a['path'];
            $fileB = $b['path'];

            // 获取文件的创建时间
            $timeA = filectime($fileA);
            $timeB = filectime($fileB);

            // 倒序排列
            return $timeB - $timeA;
        });

        // 对子目录递归调用排序
        foreach ($treeData as &$item) {
            if (isset($item['children'])) {
                $this->sortByCreateTimeDesc($item['children']);
            }
        }
    }

    public function fetchFileData(Request $request){
        $params = $request->post();
        $name = $params['name'];
        if($name == 'MM0120j'){
           $data =  $this->{$name}($params['path']);
        }elseif ($name == 'SD003Oj'){
            $data =  $this->{$name}($params['path']);
        }elseif ($name == 'MM004Ij'){ // 收货结果
            $data =  $this->{$name}($params['path']);
        }elseif ($name == 'MM009Oj'){ // 收货结果
            $data =  $this->{$name}($params['path']);
        }elseif ($name == 'SD032Oj'){ // 其他发货
            $data =  $this->{$name}($params['path']);
        }

        return CatchResponse::success($data);
    }
    private function SD032Oj($path){
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $full_path = $baseDir . '/' . $path;

        $file_content = file_get_contents($full_path);
        if ($file_content === false) {
            die("Failed to read the file");
        }

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);
        $data = [];

        $newKeys = [
            'SelfUseSlipID',
            'SelfUseCode',
            'CreateDate',
            'SelfUseDate',
            'MakerName',
            'ShipFrom',
            'ShipTo',
            'Carrier',
            'SellerID',
            'BuyerID',
            'ShipmentTerm',
            'ShipmentMethod',
            'Comments',
            'DateLastUpdated',
            'WarehouseID',
            'DocDate',
            'AddressName',
            'AR',
            'AL1',
            'AC',
            'OfficePhone',
            'DepartmentName',
            'ContactName',
            'CarrierOfficePhone',
            'CarrieerContactName',
            'Fax',
            'ZipCode',
            'Auditer',
            'Type',
            'SelfUseSlipDetailID',
            'SelfUseSlipID',
            'ItemID',
            'UMCode',
            'Qty',
            'BaseQty',
            'WarehouseID',
            'SNMgmt',
            'SerialNo',
            'ValuationType',
            'MovementType',
            'ShippingCondition',
            'VendorItemCode',
            'CustomerPONumber'
        ];

        foreach ($lines as $key => $line) {
            if (trim($line) === '') {// 跳过空行
                continue;
            }
            $line = str_replace("\r", "", $line);
            // 将每一行按一个制表符拆分成数组
            $fields = explode("\t", $line);

            $newSubArray = [];
            foreach ($fields as $oldKey => $value) {
                // 如果原来的键是数字，且在新键数组的范围内，则使用对应位置的新键，否则保留原键
                $newKey = isset($newKeys[$oldKey]) ? $newKeys[$oldKey] : $oldKey;
                $newSubArray[$newKey] = $value;
            }

            $newSubArray['id'] = $key + 1;

            $data[] = $newSubArray;
        }

        return $data;
    }
    private function MM009Oj($path){
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $full_path = $baseDir . '/' . $path;

        $file_content = file_get_contents($full_path);
        if ($file_content === false) {
            die("Failed to read the file");
        }

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);
        $data = [];

        $newKeys = [
            'TransferID',
            'TransferCode',
            'Comments',
            'MakerName',
            'TransferDate',
            'Status',
            'DateLastUpdated',
            'CreateDate',
            'TransferReason',
            'OrgID',
            'FromWarehouseID',
            'ToWarehouseID',
            'DocDate',
            'ATTR1',
            'ATTR2',
            'ATTR3',
            'ATTR4',
            'ATTR5',
            'ATTR6',
            'ATTR11',
            'ATTR12',
            'AddressName',
            'AR',
            'AL1',
            'AC',
            'OfficePhone',
            'DepartmentName',
            'ContactName',
            'Carrier',
            'Fax',
            'ZipCode',
            'Auditor(CustomerNumber)',
            'TransferDetailID',
            'Qty',
            'Remark',
            'TransferID_1',
            'InBaseQty',
            'OutBaseQty',
            'ItemID',
            'SerialNo',
            'MovementType',
            'ValuationType',
            'VendorItemCode'
        ];

        foreach ($lines as $key => $line) {
            if (trim($line) === '') {// 跳过空行
                continue;
            }
            $line = str_replace("\r", "", $line);
            // 将每一行按一个制表符拆分成数组
            $fields = explode("\t", $line);

            $newSubArray = [];
            foreach ($fields as $oldKey => $value) {
                // 如果原来的键是数字，且在新键数组的范围内，则使用对应位置的新键，否则保留原键
                $newKey = isset($newKeys[$oldKey]) ? $newKeys[$oldKey] : $oldKey;
                $newSubArray[$newKey] = $value;
            }

            $newSubArray['id'] = $key + 1;

            $data[] = $newSubArray;
        }

        return $data;
    }
    private function MM0120j($path){
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $full_path = $baseDir . '/' . $path;

        $file_content = file_get_contents($full_path);
        if ($file_content === false) {
            die("Failed to read the file");
        }

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);
        $data = [];

        $newKeys = [
            'ReceiptID',
            'OrgID',
            'ShipFrom',
            'ShipTo',
            'SellerID',
            'BuyerID',
            'ReceiptType',
            'ReceiptCode',
            'ReceiveDate',
            'RelatedTranType',
            'RefrenceNo',
            'Comments',
            'WareHouseID',
            'ReceiptDetailID',
            'ReceiptID1',
            'ItemID',
            'DeliveryDetailID',
            'OrderID',
            'OrderDetailID',
            'QtyShipped',
            'QtyReceived',
            'QtyInspected',
            'QtyAccepted',
            'QtyInvalid',
            'ComplaintReasonCode',
            'InvStatus',
            'Comments_UoM',
            'WarehouseID',
            'BaseQty',
            'MovementType',
            'ValuationType',
            'InvoiceNumber',
            'VendorItemCode'
        ];

        foreach ($lines as $key => $line) {
            if (trim($line) === '') {// 跳过空行
                continue;
            }
            $line = str_replace("\r", "", $line);
            // 将每一行按一个制表符拆分成数组
            $fields = explode("\t", $line);

            $newSubArray = [];
            foreach ($fields as $oldKey => $value) {
                // 如果原来的键是数字，且在新键数组的范围内，则使用对应位置的新键，否则保留原键
                $newKey = isset($newKeys[$oldKey]) ? $newKeys[$oldKey] : $oldKey;
                $newSubArray[$newKey] = $value;
            }

            $newSubArray['id'] = $key + 1;

            $data[] = $newSubArray;
        }

        return $data;
    }

    //指令：销售发货
    private function SD003Oj($path){
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $full_path = $baseDir . '/' . $path;

        $file_content = file_get_contents($full_path);
        if ($file_content === false) {
            die("Failed to read the file");
        }

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);
        $data = [];

        $newKeys = [
            'DeliveryID',
            'DeliveryCode',
            'CreateDate',
            'DeliveryDate',
            'MakerName',
            'ShipFrom',
            'ShipTo',
            'Carrier',
            'SellerID',
            'BuyerID',
            'SalesRepID',
            'RefrenceNo',
            'ShipmentTerm',
            'ShipmentMethod',
            'Comments',
            'DateLastUpdated',
            'WarehouseID',
            'DocDate',
            'AddressName',
            'AR',
            'AL1',
            'AC',
            'OfficePhone',
            'DepartmentName',
            'ContactName',
            'CarrierOfficePhone',
            'CarrieerContactName',
            'Install1',
            'Install2',
            'Install3',
            'Install4',
            'Install5',
            'Install6',
            'Install7',
            'Install8',
            'Install9',
            'Install10',
            'Install11',
            'Install12',
            'Install13',
            'Install14',
            'Install15',
            'Reservised1',
            'Reservised2',
            'Reservised3',
            'Reservised4',
            'Reservised5',
            'Fax',
            'ZipCode',
            'Auditer',
            'DeliveryDetailID',
            'DeliveryID1',
            'OrderCode',
            'OrderTypeID',
            'PaymentMethod',
            'OrderDetailID',
            'ItemID',
            'UMCode',
            'Qty',
            'BaseQty',
            'WarehouseID1',
            'AllocFlag',
            'SNMgmt',
            'SerialNo',
            'ValuationType',
            'MovementType',
            'ShippingCondition',
            'VendorItemCode'
        ];

        foreach ($lines as $key => $line) {
            if (trim($line) === '') {// 跳过空行
                continue;
            }
            $line = str_replace("\r", "", $line);
            // 将每一行按一个制表符拆分成数组
            $fields = explode("\t", $line);

            $newSubArray = [];
            foreach ($fields as $oldKey => $value) {
                // 如果原来的键是数字，且在新键数组的范围内，则使用对应位置的新键，否则保留原键
                $newKey = isset($newKeys[$oldKey]) ? $newKeys[$oldKey] : $oldKey;
                $newSubArray[$newKey] = $value;
            }

            $newSubArray['id'] = $key + 1;

            $data[] = $newSubArray;
        }

        return $data;
    }

    //结果：采购收货
    private function MM004Ij($path){
        $baseDir =  app()->getRootPath() . 'public/edi';  // 根目录 '/public/edi';  // 根目录
        $full_path = $baseDir . '/' . $path;

        $file_content = file_get_contents($full_path);
        if ($file_content === false) {
            die("Failed to read the file");
        }

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);
        $data = [];

        $newKeys = [
            'ReceiptID',
            'OrgID',
            'ShipFrom',
            'ShipTo',
            'SellerID',
            'BuyerID',
            'ReceiptType',
            'ReceiptCode',
            'ReceiveDate',
            'RelatedTranType',
            'RefrenceNo',
            'Comments',
            'WareHouseID',
            'ReceiptDetailID',
            'ReceiptID1',
            'ItemID',
            'DeliveryDetailID',
            'OrderID',
            'OrderDetailID',
            'QtyShipped',
            'QtyReceived',
            'QtyInspected',
            'QtyAccepted',
            'QtyInvalid',
            'ComplaintReasonCode',
            'InvStatus',
            'Comments_UoM',
            'WarehouseID',
            'BaseQty',
            'MovementType',
            'ValuationType',
        ];

        foreach ($lines as $key => $line) {
            if (trim($line) === '') {// 跳过空行
                continue;
            }
            $line = str_replace("\r", "", $line);
            // 将每一行按一个制表符拆分成数组
            $fields = explode("\t", $line);

            $newSubArray = [];
            foreach ($fields as $oldKey => $value) {
                // 如果原来的键是数字，且在新键数组的范围内，则使用对应位置的新键，否则保留原键
                $newKey = isset($newKeys[$oldKey]) ? $newKeys[$oldKey] : $oldKey;
                $newSubArray[$newKey] = $value;
            }

            $newSubArray['id'] = $key + 1;

            $data[] = $newSubArray;
        }

        return $data;
    }

    //EDI回传数据文件
    public function ediDataReturn(CatchAuth $auth){
        //类型
        $request = new ThinkRequest;
        $type = $request::post('type');
        $record_id = $request::post('record_id');

        Db::startTrans();
        try {
            if($type == '入库'){
                $file_data =  $this->return_MM004Ij($record_id);
                $write_file_name = 'MM004Ij';
            }elseif ($type == '销售出库'){
                $file_data =  $this->return_SD004Ij($record_id);
                $write_file_name = 'SD004Ij';//销售发货
            }elseif ($type == '其他出库'){
                $file_data =  $this->return_SD033Ij($record_id);
                $write_file_name = 'SD033Ij';//其他发货
            }elseif ($type == '移库'){
                $file_data =  $this->return_MM025Ij($record_id);
                $write_file_name = 'MM025Ij';//移库
            }else{
                throw new Exception('暂不支持');
            }

            $write_file_data = $this->array2WriteData($file_data);

            $ftpServer = "47.103.145.88";
            $ftpUsername = "zhq666";
            $ftpPassword = "4r4faTfbADCY7bRZ";
            $remoteRootDir = "/default/abc";
            $localRootDir = "/Users/macos/Desktop/cigisped/php/public/edi";

//            $ftpServer = "139.224.81.243";
            $ftpServer = "47.101.140.234";
            $ftpUsername = "JYL";
            $ftpPassword = "XE^JK%euRxBm";
            $remoteRootDir = "/JYL/trans";
            $localRootDir = "/home/wwwroot/customs-php/public/edi";

            $ftpClient = new FTPClient($ftpServer, $ftpUsername, $ftpPassword,true); // 实例化 FTPClient 类
            if (!$ftpClient->connect())  throw new Exception('FTP链接失败');
//            $ftpClient->set_output(true);

            //写入本地备份文件
            $current = date('YmdHis') . '_' .  mt_rand(1000,9999);
            writeOperationLog($write_file_data , "EdiBackup/{$write_file_name}/$current");

            if(! $ftpClient->writeToFile($write_file_name,$write_file_data,$remoteRootDir)){
                throw new Exception('EDI文件写入失败');
            }
            Db::commit();
        }catch (\Exception $e ){
            Db::rollback();
            return CatchResponse::fail('操作失败 ' . $e->getMessage());
        }
        return CatchResponse::success('操作成功');
    }

    //采购收货-结果
    private function return_MM004Ij($record_id){
        $warehousingModel = new Warehousing;
        $sonModel = new WarehousingSon;

        $warehousingResult = $warehousingModel->findBy($record_id);
        if(!$warehousingResult) throw new Exception('数据错误');

        if(1 != $warehousingResult->status) throw new Exception('该订单未完成全部入库');
        if(empty($warehousingResult->edi_json)) throw new Exception('非EDI创建的订单');
        if(1 == $warehousingResult['edi_return']) throw new Exception('数据已上传，请勿重新上传');

        $sonData = $sonModel->where('warehousing_id',$warehousingResult->warehousing_id)->select()->toArray();

        $file_data = [];
        foreach ($sonData as $son){
            $_son_edi_data = json_decode($son['edi_json'],true);
            //替换字段
            $default_num = '0.000';
            $_son_edi_data[20] = number_format($son['actual_number'],3); //收到货的数量
            $_son_edi_data[21] = $default_num; //检验通过数量
            $_son_edi_data[22] = $default_num; //接受数量
            $_son_edi_data[23] = $default_num; //无效数量
            $_son_edi_data[25] = '1'; //库存状态

            unset($_son_edi_data[31]);
            unset($_son_edi_data[32]);
            $file_data[] = $_son_edi_data;
        }

        $warehousingResult->edi_return = 1;
        if(! $warehousingResult->save()) throw new Exception('保存失败');

        return $file_data;
    }

    //销售发货
    private function return_SD004Ij($record_id){
        $WarehouseOutModel = new WarehouseOut;
        $sonModel = new WarehouseOutSon;

        $WarehouseOutResult = $WarehouseOutModel->findBy($record_id);
        if(!$WarehouseOutResult) throw new Exception('数据错误');

        if(1 != $WarehouseOutResult->status) throw new Exception('该订单未完成全部出库');
        if(empty($WarehouseOutResult->edi_json)) throw new Exception('非EDI创建的订单');
        if(1 == $WarehouseOutResult['edi_return']) throw new Exception('数据已上传，请勿重新上传');

        $sonData = $sonModel->where('warehouse_out_id',$WarehouseOutResult->warehouse_out_id)->select()->toArray();

        $file_data = [];
        foreach ($sonData as $key => $son){
            $_line = $key + 1;
            $_son_edi_data = json_decode($son['edi_json'],true);

            //替换字段
            $edi_data = [];
            if(1 == $son['if_back_sn']){// 是否有回传SN
                $sns = explode(',',$son['back_sn']);
                if((int) $son['number'] != count($sns)){
                    throw new Exception("第{$_line}行明细单回传单号数量错误");
                }
                for ($i =0;$i< (int) $son['number'];$i++ ){
                    $edi_data[0] = $_son_edi_data[0] ; //交货代码
                    $edi_data[1] = date('Ymd') ; //交货日期
                    $edi_data[2] = date('His') ; //交货时间
                    $edi_data[3] = '' ; //备注
//                    $edi_data[4] =  str_pad($_son_edi_data[50],6,'0',STR_PAD_LEFT); //交货明细编号
                    $edi_data[4] =  $_son_edi_data[50]; //交货明细编号
                    $edi_data[5] = $_son_edi_data[56]  ; //货品代码料号
                    $edi_data[6] = 1  ; //出库数量
                    $edi_data[7] = $sns[$i]; //序列号

                    $file_data[] = $edi_data;
                }

            }else{
                $edi_data[0] = $_son_edi_data[0] ; //交货代码
                $edi_data[1] = date('Ymd') ; //交货日期
                $edi_data[2] = date('His') ; //交货时间
                $edi_data[3] = '' ; //备注
//                $edi_data[4] =  str_pad($_son_edi_data[50],6,'0',STR_PAD_LEFT); //交货明细编号
                $edi_data[4] =  $_son_edi_data[50]; //交货明细编号
                $edi_data[5] = $_son_edi_data[56]  ; //货品代码料号
                $edi_data[6] = $son['out_number']  ; //出库数量
                $edi_data[7] = ''; //序列号
                $file_data[] = $edi_data;
            }
        }

        $WarehouseOutResult->edi_return = 1;
        if(! $WarehouseOutResult->save()) throw new Exception('保存失败');

        return $file_data;
    }

    //其他出库
    private function return_SD033Ij($record_id){
        $WarehouseOutModel = new WarehouseOut;
        $sonModel = new WarehouseOutSon;

        $WarehouseOutResult = $WarehouseOutModel->findBy($record_id);
        if(!$WarehouseOutResult) throw new Exception('数据错误');

        if(1 != $WarehouseOutResult->status) throw new Exception('该订单未完成全部出库');
        if(empty($WarehouseOutResult->edi_json)) throw new Exception('非EDI创建的订单');
        if(1 == $WarehouseOutResult['edi_return']) throw new Exception('数据已上传，请勿重新上传');

        $sonData = $sonModel->where('warehouse_out_id',$WarehouseOutResult->warehouse_out_id)->select()->toArray();

        $file_data = [];
        foreach ($sonData as $key => $son){
            $_line = $key + 1;
            $_son_edi_data = json_decode($son['edi_json'],true);

            //替换字段
            $edi_data = [];
            if(1 == $son['if_back_sn']){// 是否有回传SN
                $sns = explode(',',$son['back_sn']);
                if((int) $son['number'] != count($sns)){
                    throw new Exception("第{$_line}行明细单回传单号数量错误");
                }
                for ($i =0;$i< (int) $son['number'];$i++ ){
                    $edi_data[0] = $_son_edi_data[0] ; //交货代码
//                    $edi_data[1] =  str_pad($_son_edi_data[29],6,'0',STR_PAD_LEFT); //交货明细编号
                    $edi_data[1] =  $_son_edi_data[29]; //交货明细编号
                    $edi_data[2] = $_son_edi_data[31]  ; //货品代码料号
                    $edi_data[3] = $_son_edi_data[32]  ; //unit
                    $edi_data[4] = 1 ; //数量
                    $edi_data[5] = 1 ; //数量
                    $edi_data[6] = (int) $_son_edi_data[35]  ; //库位
                    $edi_data[7] = $sns[$i]; //序列号

                    $file_data[] = $edi_data;
                }
            }else{
                $edi_data[0] = $_son_edi_data[0] ; //交货代码
//                $edi_data[1] =  str_pad($_son_edi_data[29],6,'0',STR_PAD_LEFT); //交货明细编号
                $edi_data[1] =  $_son_edi_data[29]; //交货明细编号
                $edi_data[2] = $_son_edi_data[31]; //货品代码料号
                $edi_data[3] = $_son_edi_data[32]; //unit
                $edi_data[4] = (int) $_son_edi_data[33]; //数量
                $edi_data[5] = (int) $_son_edi_data[33]; //数量
                $edi_data[6] = $_son_edi_data[35]; //库位
                $edi_data[7] = ''; //序列号
                $file_data[] = $edi_data;
            }
        }

        $WarehouseOutResult->edi_return = 1;
        if(! $WarehouseOutResult->save()) throw new Exception('保存失败');

        return $file_data;
    }

    //其他出库
    private function return_MM025Ij($record_id){
        $moveModel = new MoveMain;
        //$sonModel = new WarehouseOutSon;

        $moveResult = $moveModel->findBy($record_id);
        if(!$moveResult) throw new Exception('数据错误');

        if(2 != $moveResult->move_status) throw new Exception('该订单未完成全部移库');
        if(empty($moveResult->edi_json)) throw new Exception('非EDI创建的订单');
        if(1 == $moveResult['edi_return']) throw new Exception('数据已上传，请勿重新上传');

        $edi_data = json_decode($moveResult['edi_json'] ,true);


        //$sonData = $sonModel->where('warehouse_out_id',$WarehouseOutResult->warehouse_out_id)->select()->toArray();
        $file_data = [];
        foreach ($edi_data as $key => $_son_edi_data){
            //替换字段
            $edi_data = [];

            $edi_data[0] = $_son_edi_data[1] ; //物料凭证代码
            $edi_data[1] = date('Ymd') ; //交货日期
            $edi_data[2] = date('H:i:s') ; //交货时间
            $edi_data[3] = date('Y-m-d H:i'); //处理时间
            $edi_data[4] = $_son_edi_data[10]; //从仓库
            $edi_data[5] = $_son_edi_data[11]; //到仓库
            $edi_data[6] = $_son_edi_data[38]; //商品料号
            $edi_data[7] = $_son_edi_data[39]; //序列号
            $edi_data[8] = $_son_edi_data[36]; //数量
            $edi_data[9] = $_son_edi_data[41]; //股价
            $edi_data[10] = $_son_edi_data[32]; //item id

            $file_data[] = $edi_data;
        }

        $moveResult->edi_return = 1;
        if(! $moveResult->save()) throw new Exception('保存失败');

        return $file_data;
    }

    //数组写入文件
    private function array2WriteData($data){
        // 假设有一个二维数组
//        $data = [
//            ["000146171", "55424010", "55424010", "55424010", "55424010", "55424010", "2", "0000146171", "20150115", "3", "3100046427", "", "1014", "10", "0000146171", "A33K182", "10", "3100046427", "10", "540.000", "", "", "", "", "", "", "", "PC", "1014", "540", "101"],
//            ["0000146172", "55424010", "55424010", "55424010", "55424010", "55424010", "2", "0000146172", "20150115", "3", "3100046427", "", "1014", "20", "0000146172", "A33K282", "20", "3100046427", "20", "540.000", "", "", "", "", "", "", "", "PC", "1014", "540", "101"]
//        ];
        // 转换成文本格式
        $text = '';
        foreach ($data as $row) {
            $text .= implode("\t", $row) . "\n";
        }

        return $text;
    }

    //通过文件路径数据文件插入数据库
    public function filePathToDb(CatchAuth $auth,Request $request){

        $file_name = $request->post('file_name');
        $path = parse_url($file_name)['path'];
        $full_path = app()->getRootPath() . 'public' . $path;

        try {
            $ediService = new EdiService;
            $data =  $ediService->pathToDb($full_path);

            return CatchResponse::success($data);
        }catch (\Exception $exception){
            return CatchResponse::fail('导入失败 ' . $exception->getMessage());
        }
    }
}